package com.zretc.util;


import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.*;

/** 
 *  Description : Excel相关工具类
 * 
 * @author:  chenlihuan
 * 
 * History: 2020-01-09 14:46:10   chenlihuan   Created.
 * 
 */
public class ExcelUtil {

	/**
	 * 生成excel表格
	 * @param heads 表头内容
	 * @param data  数据内容
	 * @return
	 */
	public static HSSFWorkbook creatExcel(Map<String, String> heads, List data) {

		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet();
		// 生成标题行样式
		HSSFCellStyle headStyle = creatStyle(workbook, (short) 14);
		// 生成表格内容样式
		HSSFCellStyle bodyStyle = creatStyle(workbook, (short) 10);
		// 标题元素
		List<String> keys = new ArrayList<String>(heads.keySet());
		// 像素单位
		short px = 1000;
		// 设置列宽
		for (int columnIndex = 0; columnIndex < keys.size(); columnIndex++) {

			sheet.setColumnWidth(columnIndex, 6 * px);
		}

		// 生成表格
		for (int rowNum = 0; rowNum <= data.size(); rowNum++) {

			// 创建行
			HSSFRow row = sheet.createRow(rowNum);

			for (int cellNum = 0; cellNum < keys.size(); cellNum++) {

				// 创建列
				HSSFCell cell = row.createCell(cellNum);

				// 标题
				if (rowNum == 0) {

					cell.setCellStyle(headStyle);
					cell.setCellValue(heads.get(keys.get(cellNum)));
				} else { // 内容

					cell.setCellStyle(bodyStyle);
					// 通过反射获取
					cell.setCellValue(ReflectUtil.getValue(keys.get(cellNum), data.get(rowNum - 1)));
				}
			}
		}

		return workbook;
	}

	/**
	 * 生成样式
	 * @param workbook
	 * @param size
	 * @return
	 */
	public static HSSFCellStyle creatStyle(HSSFWorkbook workbook, short size) {

		HSSFCellStyle style = workbook.createCellStyle();
		style.setAlignment((HSSFCellStyle.ALIGN_CENTER));
		style.setVerticalAlignment((HSSFCellStyle.VERTICAL_CENTER));
		style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		style.setBorderTop(HSSFCellStyle.BORDER_THIN);
		style.setBorderRight(HSSFCellStyle.BORDER_THIN);
		style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

		HSSFFont font = workbook.createFont();
		font.setFontHeightInPoints(size);
		font.setFontName("微软雅黑");
		style.setFont(font);

		return style;
	}


}
